package com.dy.yunying.biz.utils;

import com.dy.yunying.api.req.yyz.ExcelData;
import com.dy.yunying.api.req.yyz.GameAppointmentQueryList;
import com.dy.yunying.api.resp.yyz.GameAppointmentExportRes;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildExcelDocument {

	/**
	 *
	 * @param response
	 * @param list 需要导出数据
	 * @param head excel每列中文名称信息
	 * @param fileName 导出excel名称
	 * @param column excel每列英文名称信息
	 */
	public static void exportExcelData(HttpServletResponse response, List<GameAppointmentExportRes> list, String head, String fileName, String column) {
		try {
			response.reset();
			response.setHeader("content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			String fileNameUtf8 = URLEncoder.encode(fileName, "UTF8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileNameUtf8);
			response.setHeader("file-name", fileNameUtf8);
			OutputStream os = response.getOutputStream();
			ExcelData data = new ExcelData();
			SXSSFWorkbook workbook= new SXSSFWorkbook();

			// 获取字体
			Font titleFont = workbook.createFont();
			titleFont.setFontName("simsun");//设置字体名称（宋体）
			titleFont.setColor(IndexedColors.BLACK.index);//设置字体颜色 黑色
			// 设置样式
			CellStyle style = workbook.createCellStyle();

			try {
			data.setTotalItem(list.size());//求出多少条数据
			int page_size = 50000;// 定义每个sheet页数据数量
			int list_count =data.getTotalItem();
			//总数量除以每页显示条数等于页数
			int export_times = list_count % page_size > 0 ? list_count / page_size + 1 : list_count / page_size;
			//循环获取产生每页数据
			for (int m = 0; m < export_times; m++) {
				//新建sheet
				SXSSFSheet sheet = null;
				sheet = workbook.createSheet("预约用户表" + "sheet_"+ m);
				// 创建属于上面Sheet的Row，参数0可以是0～65535之间的任何一个，
				SXSSFRow header = sheet.createRow(0); // 第0行
				// 产生标题列，每个sheet页产生一个标题
				SXSSFCell cell;
				String[] headerArr = head.split(",");
				String[] columnArr = column.split(",");
				for (int j = 0; j < headerArr.length; j++) {
					cell = header.createCell((short) j);
					cell.setCellStyle(style);
					cell.setCellValue(headerArr[j]);
				}
				// 迭代数据
				if (list != null && list.size() > 0) {
					int rowNum = 1;
					int start= m*page_size;
					int  size = list_count / (page_size*(m+1)) > 0 ? page_size*(m+1) : list_count;
					for (int i = start ; i < size ; i++) {
						GameAppointmentExportRes gameAppointmentExportRes = list.get(i);
							sheet.setDefaultColumnWidth((short) 17);
							SXSSFRow row = sheet.createRow(rowNum++);
							for (int n = 0;n <columnArr.length;n++){
								row.createCell((short) n).setCellValue(getValueByFieldName(columnArr[n],gameAppointmentExportRes,true));
							}
					}
				}
			}
			}catch (Exception e) {
				e.printStackTrace();
			}
			try {
				workbook.write(os);
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据属性名称获取属性值，并将Object类型的属性值转成String
	 *
	 * @param name
	 * @param obj
	 * @param flag
	 * @return
	 */
	public static String getValueByFieldName(String name, Object obj, boolean flag) {
		String result = "";
		Object val = getValueByFieldName(name, obj);
		if (flag) {
			if (val instanceof String) {
				return (String) val;
			} else if (val instanceof Integer) {
				return "" + (int) val;
			} else if (val instanceof Long) {
				return "" + (long) val;
			} else if (val instanceof Byte) {
				return "" + (byte) val;
			} else if (val instanceof Double) {
				return "" + (double) val;
			} else if (val instanceof Float) {
				return "" + (float) val;
			} else if (val instanceof Boolean) {
				return (boolean) val ? "是" : "否";
			} else if (val instanceof Date) {
				Date value = (Date) val;
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				return format.format(value);
			} else if (val instanceof BigDecimal) {
				BigDecimal value = (BigDecimal) val;
				String d = value.toString();
				if (d.contains(".")) {
					String[] dd = d.split("\\.");
					if ("00".equals(dd[1]) || "000".equals(dd[1])) {
						return dd[0] + "";
					} else {
						return d + "";
					}
				}
				return d + "";
			} else if (val instanceof BigInteger) {
				BigInteger value = (BigInteger) val;
				return value.intValue() + "";
			} else {
				return "";
			}
		}
		return result;
	}

	/**
	 * 根据属性名称获取属性值
	 *
	 * @param name
	 * @param obj
	 * @return
	 */
	public static Object getValueByFieldName(String name, Object obj) {
		Object result = null;
		try {
			if (obj.getClass().getName().equals(Map.class.getName()) || obj.getClass().getName().equals(HashMap.class.getName())) {
				return ((Map<?, ?>) obj).get(name);
			}
			String stringLetter = name.substring(0, 1).toUpperCase();
			String getName = "get" + stringLetter + name.substring(1);
			Method getmethod0 = obj.getClass().getMethod(getName);
			result = getmethod0.invoke(obj);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return result;
	}
}
